#!/usr/bin/env python
#
# This is the GUI for the system!
# 
# The pack() and pack_forget combinations are extremely powerful!
#

import os
import sys
import Tkinter as tk

import admin
import config

class BaseWindow:
    '''
    This is the basic window wireframe. All the interaction will happen here
    (no opening up new windows, etc) so we will devise a way of using "tabs"
    where the choices chosen through the menubar will show-hide the content.
    '''

    def destroy(self, event=None):
        '''
        For now a thin wrapper for the Tk.quit() method, but may be used as
        a safety catch e.g. if one hasn't saved inventory changes before 
        quitting. I dno. Let's see how this goes.
        '''
        print "Quitting..."
        self.window.quit()

    def submit_purchase(self):
        '''
        Read all fields and submit them!
        '''
        values = []

        if self.new_purchase_fields[0].get() == "":
            self.statusbar.config(text="Preencha o nome do cliente")
            return
        elif self.new_purchase_fields[1].get() == "":
            self.statusbar.config(text="Preencha o email do cliente")
            return
        for field in self.new_purchase_fields:
            if field.get() == "":
                values.append(0)
            else:
                values.append(field.get())

        code = admin.new_purchase(
            values[0],
            values[1],
            int(values[2]),
            int(values[3]),
            int(values[4]),
            int(values[5]),
            int(values[6])
        )
        if code[0] == "unavailable":
            self.statusbar.config(text="Indisponivel no estoque: %s" % code[1])
        else:
            self.statusbar.config(text="Pedido numero %s cadastrado" % code[0])
            for field in self.new_purchase_fields:
                field.delete(0, tk.END)

    def checkorder(self):
        purchase = admin.view_purchase(
            self.ordervalue.get().split(" ")[0]
        )
        finalstring = ""
        if purchase is not None:
            finalstring += "Cliente: %s (%s)\n" % (purchase[0], purchase[1])
            if purchase[2] != 0:
                finalstring += "Sabonete de Mel: %s unidades\n" % purchase[2]
            if purchase[3] != 0:
                finalstring += "Sabonete de Patchouli: %s unidades\n" % purchase[3]
            if purchase[4] != 0:
                finalstring += "Sabonete de Papoula: %s unidades\n" % purchase[4]
            if purchase[5] != 0:
                finalstring += "Sabonete de Capim-limao: %s unidades\n" % purchase[5]
            if purchase[6] != 0:
                finalstring += "Alcool-gel: %s unidades\n" % purchase[6]

            finalstring += "Status do pedido: %s\n" % purchase[7]
            finalstring += "Criado em: %s" % purchase[8]

            self.resultsfield.config(text=finalstring)

        else:
            self.resultsfield.config(text="Transaction not found")


    def availability(self):
        '''
        Queries the database to see if there are any items still available
        '''
        product = self.menuvalue.get()
        stock = admin.view_availability(product)
        self.statusbar.config(text="Quantidade em estoque: %s" % stock)

    # These three methods change the main view of the program:
    def view_inventory(self):
        self.statusbar.config(text="Visualizando inventario")
        self.new_purchase_frame.pack_forget()
        self.ongoing_purchase_frame.pack_forget()
        self.inventory_frame.pack(expand=True, fill=tk.BOTH)

    def view_purchases(self):
        self.statusbar.config(text="Visualizando compras")
        self.new_purchase_frame.pack_forget()
        self.inventory_frame.pack_forget()
        self.ongoing_purchase_frame.pack(expand=True, fill=tk.BOTH)

    def view_new_purchase(self):
        self.statusbar.config(text="Cadastre uma nova compra")
        self.ongoing_purchase_frame.pack_forget()
        self.inventory_frame.pack_forget()
        self.new_purchase_frame.pack(expand=True, fill=tk.BOTH)


    def update_ongoing(self):
        ongoing = admin.get_transactions("pendente")
        raw = []

        for item in ongoing:
            raw.append("%s - %s" % (item[0], item[1]))
        
        return tuple(raw)


    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Gerenciador de inventario e vendas")
        self.window.geometry("600x500")

        self.window.bind("<Control-q>", self.destroy)
        
        # Base canvas on which all content will be placed:
        self.canvas = tk.Frame(self.window)

        # Show-hide canvases for each of the "application windows"
        self.new_purchase_frame = tk.Frame(self.canvas)
        self.ongoing_purchase_frame = tk.Frame(self.canvas)
        self.inventory_frame = tk.Frame(self.canvas)
        
        # This statusbar will be present at all times in the interface:
        self.statusbar = tk.Label(self.window)

        # Menubar to go full WIMP
        self.menubar = tk.Menu(self.window)
        self.filemenu = tk.Menu(self.menubar, tearoff=False)
        self.filemenu.add_command(label="Sair", command=self.destroy, underline=0)

        self.viewmenu = tk.Menu(self.menubar, tearoff=False)
        self.viewmenu.add_command(label="Nova compra", 
            command=self.view_new_purchase, underline=0)
        self.viewmenu.add_command(label="Inventario", 
            command=self.view_inventory, underline=0)
        self.viewmenu.add_command(label="Compras", 
            command=self.view_purchases, underline=0)

        self.menubar.add_cascade(label="Arquivo", menu=self.filemenu, underline=0)
        self.menubar.add_cascade(label="Visualizar", menu=self.viewmenu, underline=0)
        self.window.config(menu=self.menubar)

        #-----------------------
        #
        # Packing content for NEW PURCHASE
        #
        #-----------------------
        self.new_purchase_fields = []

        self.namelabel = tk.Label(self.new_purchase_frame, text="Nome do cliente:")
        self.namefield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.namefield)

        self.emaillabel = tk.Label(self.new_purchase_frame, text="Email do cliente:")
        self.emailfield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.emailfield)

        self.mellabel = tk.Label(self.new_purchase_frame, text="Qtd Sabonete de mel:")
        self.melfield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.melfield)

        self.patchoulilabel = tk.Label(self.new_purchase_frame, text="Qtd Sabonete de Patchouli:")
        self.patchoulifield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.patchoulifield)

        self.papoulalabel = tk.Label(self.new_purchase_frame, text="Qtd Sabonete de Papoula:")
        self.papoulafield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.papoulafield)

        self.capimlabel = tk.Label(self.new_purchase_frame, text="Qtd Sabonete de Capim-limao:")
        self.capimfield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.capimfield)

        self.alcoollabel = tk.Label(self.new_purchase_frame, text="Qtd Alcool-gel:")
        self.alcoolfield = tk.Entry(self.new_purchase_frame)
        self.new_purchase_fields.append(self.alcoolfield)

        self.submit = tk.Button(self.new_purchase_frame, text="Cadastrar", 
            command=self.submit_purchase)

        self.namelabel.pack(fill="x")
        self.namefield.pack(fill="x")
        self.emaillabel.pack(fill="x")
        self.emailfield.pack(fill="x")

        self.mellabel.pack()
        self.melfield.pack()
        self.patchoulilabel.pack()
        self.patchoulifield.pack()
        self.papoulalabel.pack()
        self.papoulafield.pack()
        self.capimlabel.pack()
        self.capimfield.pack()
        self.alcoollabel.pack()
        self.alcoolfield.pack() 

        self.submit.pack()

        #-----------------------
        #
        # Packing content for ONGOING TRANSACTIONS
        #
        #-----------------------
        self.coderow = tk.Frame(self.ongoing_purchase_frame)

        self.orderframe = tk.Frame(self.coderow)
        self.ordervalue = tk.StringVar(self.window)
        self.ordervalue.set("Clique para escolher")
        self.orderdropdown = apply(tk.OptionMenu, (self.orderframe, 
            self.ordervalue) + self.update_ongoing())
        
        self.codelabel = tk.Label(self.coderow, text="Codigo do pedido")

        self.checkbutton = tk.Button(self.coderow, text="Checar",
            command=self.checkorder)

        self.resultsarea = tk.Frame(self.ongoing_purchase_frame)
        self.resultslabel = tk.Label(self.resultsarea, text="Detalhes do pedido")
        self.resultsfield = tk.Label(self.resultsarea, text="")

        self.coderow.pack(expand=False, fill=tk.BOTH)
        self.resultsarea.pack(expand=True, fill=tk.BOTH)
        self.resultslabel.pack()
        self.resultsfield.pack(expand=True, fill=tk.BOTH)

        self.codelabel.pack(side="left")
        self.orderframe.pack(side="left", expand=True, fill="x")
        self.orderdropdown.pack(side="left", expand=True, fill="x")
        self.checkbutton.pack(side="left")
        

        #-----------------------
        #
        # Packing content for INVENTORY
        #
        #-----------------------

        # Stuff for Dropdown menu:
        self.menuvalue = tk.StringVar(self.window)
        self.menuvalue.set("Clique para escolher")
        self.inventoryframe = tk.Frame(self.inventory_frame)
        self.dropdown = apply(tk.OptionMenu, (self.inventoryframe, 
            self.menuvalue) + config.products)

        self.checker = tk.Button(self.inventory_frame, text="Checar disponibilidade", 
            command=self.availability)

        self.inventoryframe.pack(side="left", expand=1)
        self.dropdown.pack(expand=1)
        self.checker.pack(side="right")



        #-----------------------
        #
        # Packing content for CLIENT INFORMATION 
        #
        #-----------------------

        # TODO!


        # Pack them up.
        self.canvas.pack(expand=True)
        self.new_purchase_frame.pack(expand=True, fill=tk.BOTH)
        self.ongoing_purchase_frame.pack(expand=True, fill=tk.BOTH)
        self.inventory_frame.pack(expand=True, fill=tk.BOTH)
        self.new_purchase_frame.pack_forget()
        self.ongoing_purchase_frame.pack_forget()
        self.inventory_frame.pack_forget()
        self.statusbar.pack()

    def main(self):
        self.statusbar.config(text="Ready to roll")
        self.window.mainloop()



if __name__ == "__main__":
    app = BaseWindow()
    app.main()
